package org.lanqiao.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.lanqiao.bean.Company;
import org.lanqiao.bean.User;
import org.lanqiao.lg.dao.CompanyDao;
import org.lanqiao.lg.dao.impl.CompanyDaoImpl;
import org.lanqiao.sjx.dao.UserDao;
import org.lanqiao.sjx.dao.impl.UserImpl;
import org.lanqiao.tools.BaseServlet;

import com.google.gson.Gson;

@WebServlet("/Load")
public class Login extends BaseServlet {
	Gson gson = new Gson();
	CompanyDao comdao = new CompanyDaoImpl();
	UserDao dao=new UserImpl();

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.request = request;
		this.response = response;
		redata.setMsg("");
		login();

		response.getWriter().write(gson.toJson(redata));
	}

	private void login() {
		String num = getString("b1");
		String pwd = getString("password");
		if (redata.getMsg() != "") {
			redata.setCode(3);
			redata.setData("");
			return;
		}
//		先判断该用户是否在 个人用户表
		User user = dao.selectUserByb1Pwd(num, pwd);
		System.out.println(user);

		if (user !=null) {
			Integer id = user.getId();
//			把标识存入Session会话里面
			HttpSession session = request.getSession();
			session.setAttribute("id", id);
			session.setAttribute("typeU", "1");// 个人用户 标识是 1
			System.out.println(request.getSession().getId() + "/id=" + id + "/loginU");
			redata.setCode(2);
			redata.setMsg("Login User 成功");
			redata.setData(1);
			return;
		} else {
//			如果在个人用户表查不到，去公司表查
			Long j= comdao.CompanyLogin(num, pwd);
			if (j > 0) {
				Integer id = comdao.selectCompanyId(new Company(num, pwd));
//				把标识存入Session会话里面
				HttpSession session = request.getSession();
				session.setAttribute("id", id);
				session.setAttribute("typeU", "2");// 公司用户 标识是 2
				System.out.println(request.getSession().getId() + "/id=" + id + "/loginC");
				redata.setCode(2);
				redata.setMsg("Login Company 成功");
				redata.setData(2);
				return;
			}else {
				redata.setCode(3);
				redata.setMsg("帐号密码错误");
				redata.setData(user);
				return;
			}
		}

	}
}
